<template>
  <div>
    <a-drawer
      title="开票"
      :width="720"
      :visible="visible"
      :body-style="{ paddingBottom: '80px' }"
      @close="close"
    >
      <a-form  ref="formRef" :model="formState" :rules="formRules" layout="vertical" hide-required-mark>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="收入" name="income" :rules="formRules.income">
              <a-input readOnly
                v-model:value="formState.income"
                style="width: 100%"
                addon-before="￥"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="支出" name="expenditure" :rules="formRules.expenditure">
              <a-input readOnly
                v-model:value="formState.expenditure"
                style="width: 100%"
                addon-before="￥"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="总单数" name="total" :rules="formRules.total">
              <a-input readOnly
                v-model:value="formState.total"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="利润" name="profit" :rules="formRules.profit">
              <a-input readOnly
                v-model:value="formState.profit"
                style="width: 100%"
                addon-before="￥"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="客户" name="id_client" :rules="formRules.id_client">
              <a-select
                showSearch
                v-model:value="formState.id_client"
                disabled
                allowClear
                optionFilterProp="children"
                :options="clients"
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所属公司" name="id_company" :rules="formRules.id_company">
              <a-select
                showSearch
                v-model:value="formState.id_company"
              >
                <a-select-option v-for="c of companies" :key="c.value" :value="c.value">{{c.label}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="开票金额" name="invoice_amount" :rules="formRules.invoice_amount">
              <a-input
                readOnly
                v-model:value="formState.invoice_amount"
                style="width: 100%"
                addon-before="￥"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="发票号" name="invoice_no" :rules="formRules.invoice_no">
              <a-input
                v-model:value="formState.invoice_no"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="开票日期" name="invoice_date" :rules="formRules.invoice_date">
              <a-date-picker
                :value-format="dateFormat"
                v-model:value="formState.invoice_date"
                style="width: 100%"
                :get-popup-container="trigger => trigger.parentNode"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="备注" name="memo" :rules="formRules.memo">
              <a-textarea
                v-model:value="formState.memo"
                :rows="4"
                placeholder="Please enter your description in case you forget something!"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="close">
          取消
        </a-button>
        <a-button type="primary" @click="handleOk">
          提交
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import moment from 'moment'
import _, { pick } from "lodash";
import { postAction } from "@/utils/request";
import { message } from 'ant-design-vue';

// 定义 props
const props = defineProps(['clients', 'companies']);

// 响应式数据
const formRef = ref(null); // 表单引用
const dateFormat = ref('YYYY-MM-DD');
const visible = ref(false);

// 表单数据
const formState = ref({
  income: undefined,
  expenditure: undefined,
  total: undefined,
  profit: undefined,
  id_client: undefined,
  id_company: undefined,
  invoice_amount: undefined,
  invoice_no: undefined,
  invoice_date: undefined,
  memo: undefined
});

// 表单验证规则
const formRules = ref({
  income: [
    { required: true, message: '收入不能为空', trigger: 'blur' }
  ],
  expenditure: [
    { required: true, message: '支出不能为空', trigger: 'blur' }
  ],
  total: [
    { required: true, message: '总单数不能为空', trigger: 'blur' }
  ],
  profit: [
    { required: true, message: '利润不能为空', trigger: 'blur' }
  ],
  id_client: [
    { required: true, message: '客户不能为空', trigger: 'change' }
  ],
  id_company: [
    { required: true, message: '入帐公司不能为空', trigger: 'change' }
  ],
  invoice_amount: [
    { required: true, message: '开票金额不能为空', trigger: 'blur' }
  ],
  invoice_no: [
    { required: true, message: '发票号不能为空', trigger: 'blur' }
  ],
  invoice_date: [
    { required: true, message: '入帐日期不能为空', trigger: 'change' }
  ],
  memo: []
});
//// simple vars
const url = {
  saveInvoicedBillRecord: '/yg/finance/saveInvoicedBillRecord',
}

// methods
// 显示抽屉函数
const showBillToVoice = (param) => {
  visible.value = true;
  nextTick(() => {
    formState.value = {
      ...formState.value,
      invoice_amount: param.profit,
      ...pick(param, ['id_client', 'id_company', 'income', 'expenditure', 'profit', 'total', 'id_invoiced_bills', 'update_by'])
    };
  });
};
// 关闭函数
const close = () => {
  visible.value = false;
};
const emit = defineEmits(['sync'])
// 保存函数
const save = () => {
    postAction(url.saveInvoicedBillRecord, formState.value).then(response => {
      //console.error("id:",response.data.id)
      if (response.data && response.data.id > 0) {
        formState.value.id = response.data.id;
        message.success("保存成功");
        close()
        emit("sync",2)
      } else {
        message.error("保存失败");
      }
    })
    .catch(error => {
      message.error("保存失败");
      console.log('error', error);
    });
};
// 处理提交函数
const handleOk = async () => {
  await nextTick(() => {
    formRef.value?.validate()
        .then(() => {
          save(formState.value)
        })
        .catch(error => {
          message.warning("表单信息验证失败");
          console.log('error', error);
        });
  })
}
defineExpose({
  showBillToVoice
});
</script>

